package cn.iocoder.yudao.module.measure.events.listener;


import cn.iocoder.yudao.module.measure.dal.dataobject.upload.BusinessDeviceUploadData;
import cn.iocoder.yudao.module.measure.events.BusinessDeviceUploadDataEvent;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApi;
import com.influxdb.client.WriteOptions;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Collections;

/**
 * 写入influxdb
 *
 * 禁用时 注释下方Component注解即可
 */
@Component
@Slf4j
public class DeviceWriteToInfluxDBListener implements ApplicationListener<BusinessDeviceUploadDataEvent> {

    @Value("${influxdb.bucket}")
    private String INFLUXDB_BUCKET;
    @Value("${influxdb.org}")
    private String INFLUXDB_ORG;

    @Autowired
    private InfluxDBClient influxDBClient;

    @Async("applicationMeasureEventTaskExecutor")
    @Override
    public void onApplicationEvent(BusinessDeviceUploadDataEvent event) {
        BusinessDeviceUploadData data = event.getSource();
        Point point = Point
                .measurement("deviceUploadData")
                .addTag("measurePointId", String.valueOf(data.getDeviceId()))
                .addTag("dataType",data.getDataType())
                .addTag("dataUnit",data.getDataUnit())
                .addField("dataValue",data.getDataValue())
                .time(Instant.now(), WritePrecision.NS);

        WriteOptions writeOption = getDefaultWriteOptions();
        try (WriteApi writeApi = influxDBClient.makeWriteApi(writeOption)) {
            writeApi.writePoints(INFLUXDB_BUCKET, INFLUXDB_ORG, Collections.singletonList(point));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private WriteOptions getDefaultWriteOptions(){
        WriteOptions writeOptions = WriteOptions.builder()
                .batchSize(5000)
                .flushInterval(1000)
                .bufferLimit(10000)
                .jitterInterval(1000)
                .retryInterval(5000)
                .build();
        return writeOptions;
    }
}
